﻿using System.Drawing.Imaging;
using System.Drawing;
using SkiaSharp;

namespace MyERP.Services
{
    /// <summary>
    /// 服务类，用于生成验证码图片和验证码文本
    /// </summary>
    public class CaptchaService
    {
        //生成随机验证码文本
        public string GenerateCaptchaCode(int length = 4)
        {
            const string chars = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
            var random = new Random();
            return new string(Enumerable.Repeat(chars, length)
                .Select(s => s[random.Next(s.Length)]).ToArray());
        }

        // 生成验证码图片
        public byte[] GenerateCaptchaImage(string captchaText)
        {
            // 创建图像
            var info = new SKImageInfo(120, 40);
            using (var surface = SKSurface.Create(info))
            {
                var canvas = surface.Canvas;
                canvas.Clear(SKColors.White);

                // 绘制验证码文本
                using (var paint = new SKPaint())
                {
                    paint.Color = SKColors.Black;
                    paint.TextSize = 24;
                    paint.Typeface = SKTypeface.FromFamilyName("Arial", SKFontStyle.Bold);
                    canvas.DrawText(captchaText, 10, 28, paint);
                }

                // 添加干扰线
                var random = new Random();
                for (int i = 0; i < 5; i++)
                {
                    using (var paint = new SKPaint())
                    {
                        paint.Color = new SKColor((byte)random.Next(256), (byte)random.Next(256), (byte)random.Next(256));
                        canvas.DrawLine(random.Next(0, 120), random.Next(0, 40), random.Next(0, 120), random.Next(0, 40), paint);
                    }
                }

                // 将图像保存为字节数组
                using (var image = surface.Snapshot())
                using (var data = image.Encode(SKEncodedImageFormat.Png, 100))
                using (var stream = new MemoryStream())
                {
                    data.SaveTo(stream);
                    return stream.ToArray();
                }
            }
        }
    }
}
